package hong.jun.details;

import hong.jun.domain.Permission;
import hong.jun.domain.User;
import hong.jun.mapper.PermissionMapper;
import hong.jun.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//加载用户信息，和权限信息
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("无效的用户名");
        }

        //2.查询用户的权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(user.getId());

        //把权限列表转换一下
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        permissions.forEach(permission -> {
            //user:list
            authorities.add(new SimpleGrantedAuthority(permission.getExpression()));
        });


        //3.返回UserDetails
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                username, user.getPassword(), authorities);
        return userDetails;
    }
}
